package com.example.exception.global;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Collections;

/**
 * @author edz
 */
@ControllerAdvice
@Slf4j
public class ExceptionControllerAdvice {

    //    @ExceptionHandler(value = {Exception.class})
//    @ResponseBody
    public void handlerControllerException1(HttpServletRequest httpServletRequest, HttpServletResponse response, Exception e) {
        log.error("全局异常捕获URI：{}", httpServletRequest.getRequestURL());
        log.error("全局异常" + e);
        response.setCharacterEncoding("UTF-8");
        try {
            // 中文乱码的一种解决方案
            response.getWriter().write(e.getMessage());
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }


    @ExceptionHandler(value = {Exception.class})
    @ResponseBody
    public ResponseEntity<String> handlerControllerException2(HttpServletRequest httpServletRequest, HttpServletResponse response, Exception e) {
        log.error("全局异常捕获URI：{}", httpServletRequest.getRequestURL());
        log.error("全局异常" + e);
        MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
        headers.add("content-type", "text/plain;charset=utf-8");
        return new ResponseEntity<>(e.getMessage(), headers, HttpStatus.valueOf(HttpStatus.UNAUTHORIZED.value()));
    }
}
